<?php
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/pushplus.php';

// 检查登录
if (!isLoggedIn()) {
    redirect('index.php', '请先登录', 'warning');
}

$userInfo = getUserInfo();

// 生成CSRF令牌防止重复提交
if (!isset($_SESSION['submit_token'])) {
    $_SESSION['submit_token'] = bin2hex(random_bytes(32));
}

// 获取配置选项
$db = getDB();
$deliveryLocations = getConfigOptions('delivery_location');
$orderPlatforms = getConfigOptions('order_platform');

// 处理报单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 检查重复提交
    $token = $_POST['csrf_token'] ?? '';
    if (empty($token) || $token !== ($_SESSION['submit_token'] ?? '')) {
        redirect('orders.php', '请勿重复提交订单', 'warning');
    }
    
    // 清除token，防止重复提交
    unset($_SESSION['submit_token']);
    
    $product_name = $_POST['product_name'] ?? '';
    $delivery_location = $_POST['delivery_location'] ?? '';
    $order_platform = $_POST['order_platform'] ?? '';
    $tracking_no = $_POST['tracking_no'] ?? '';
    $order_amount = $_POST['order_amount'] ?? '';
    $payment_method = $_POST['payment_method'] ?? 'owner_paid';
    $notes = $_POST['notes'] ?? '';
    $pickup_code = $_POST['pickup_code'] ?? '';
    $is_signed = isset($_POST['is_signed']) ? intval($_POST['is_signed']) : 0;
    
    // 验证必填字段
    if (empty($product_name) || empty($delivery_location) || empty($order_platform) || empty($tracking_no) || empty($order_amount)) {
        $error = '请填写所有必填字段';
    } elseif (!is_numeric($order_amount) || $order_amount <= 0) {
        $error = '下单金额必须是正数';
    } elseif (strlen($tracking_no) > 18) {
        $error = '物流单号不能超过18位，请检查是否填写的是快递单号，不要填写订单号';
    } else {
        // 检查物流单号是否已存在
        $stmt = $db->prepare("SELECT id FROM orders WHERE tracking_no = ?");
        $stmt->execute([$tracking_no]);
        if ($stmt->fetch()) {
            $error = '该物流单号已存在';
        } else {
            // 处理订单截图上传
            $order_screenshot = null;
            if (isset($_FILES['order_screenshot']) && $_FILES['order_screenshot']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = uploadFile($_FILES['order_screenshot'], 'order_screenshot');
                if ($uploadResult['success']) {
                    $order_screenshot = $uploadResult['filename'];
                } else {
                    $error = '订单截图上传失败：' . $uploadResult['message'];
                }
            }
            
            if (!isset($error)) {
                // 插入订单数据
                $stmt = $db->prepare("INSERT INTO orders (user_id, product_name, delivery_location, order_platform, tracking_no, order_amount, payment_method, notes, pickup_code, order_screenshot, is_signed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$userInfo['id'], $product_name, $delivery_location, $order_platform, $tracking_no, $order_amount, $payment_method, $notes, $pickup_code, $order_screenshot, $is_signed])) {
                    $orderId = $db->lastInsertId();
                    
                    // 发送通知给管理员
                    try {
                        notifyAdminOrderSubmitted($orderId, $userInfo, [
                            'product_name' => $product_name,
                            'delivery_location' => $delivery_location,
                            'order_platform' => $order_platform,
                            'tracking_no' => $tracking_no,
                            'order_amount' => $order_amount,
                            'payment_method' => $payment_method,
                            'notes' => $notes
                        ]);
                    } catch (Exception $e) {
                        // 推送失败不影响正常流程
                    }
                    
                    redirect('orders.php', '报单提交成功，请等待管理员审核', 'success');
                } else {
                    // 如果订单插入失败，删除已上传的图片
                    if ($order_screenshot) {
                        deleteFile($order_screenshot, 'order_screenshot');
                    }
                    $error = '报单提交失败，请重试';
                }
            }
        }
    }
}

include __DIR__ . '/header.php';
?>

<div class="container">
    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">
                        <i class="bi bi-plus-circle"></i> 提交报单
                    </h4>
                </div>
                <div class="card-body">
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['submit_token']; ?>">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="product_name" class="form-label">
                                    <i class="bi bi-box text-primary"></i> 商品名称 <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="product_name" name="product_name" 
                                       placeholder="请输入商品名称" required>
                                <div class="invalid-feedback">
                                    请输入商品名称
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="delivery_location" class="form-label">
                                    <i class="bi bi-geo-alt text-primary"></i> 收货地 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="delivery_location" name="delivery_location" required>
                                    <option value="">请选择收货地</option>
                                    <?php foreach ($deliveryLocations as $location): ?>
                                        <option value="<?php echo htmlspecialchars($location['option_value']); ?>">
                                            <?php echo htmlspecialchars($location['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">
                                    请选择收货地
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="order_platform" class="form-label">
                                    <i class="bi bi-shop text-primary"></i> 下单平台 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="order_platform" name="order_platform" required>
                                    <option value="">请选择下单平台</option>
                                    <?php foreach ($orderPlatforms as $platform): ?>
                                        <option value="<?php echo htmlspecialchars($platform['option_value']); ?>">
                                            <?php echo htmlspecialchars($platform['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">
                                    请选择下单平台
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="tracking_no" class="form-label">
                                    <i class="bi bi-truck text-primary"></i> 物流单号 <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="tracking_no" name="tracking_no" 
                                       placeholder="请输入物流单号" maxlength="18" required>
                                <div class="invalid-feedback">
                                    请输入物流单号
                                </div>
                                <div class="form-text text-warning">
                                    <i class="bi bi-exclamation-triangle"></i> 
                                    请填写快递单号（不超过18位），不要填写订单号
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="order_amount" class="form-label">
                                    <i class="bi bi-currency-yen text-primary"></i> 下单金额 <span class="text-danger">*</span>
                                </label>
                                <input type="number" class="form-control" id="order_amount" name="order_amount" 
                                       placeholder="请输入下单金额" step="0.01" min="0.01" required>
                                <div class="invalid-feedback">
                                    请输入有效的下单金额
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="payment_method" class="form-label">
                                    <i class="bi bi-credit-card text-primary"></i> 付款方式 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="payment_method" name="payment_method" required>
                                    <option value="owner_paid">自己付款</option>
                                    <option value="group_paid">群主垫付</option>
                                </select>
                                <div class="invalid-feedback">
                                    请选择付款方式
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="pickup_code" class="form-label">
                                    <i class="bi bi-key text-primary"></i> 取件码
                                </label>
                                <input type="text" class="form-control" id="pickup_code" name="pickup_code" 
                                       placeholder="请输入取件码" maxlength="50">
                                <div class="form-text">
                                    如有取件码请填写，也可到货后在订单页面修改添加
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="is_signed" class="form-label">
                                    <i class="bi bi-truck text-primary"></i> 是否签收
                                </label>
                                <select class="form-select" id="is_signed" name="is_signed">
                                    <option value="0">未签收</option>
                                    <option value="1">已签收</option>
                                </select>
                                <div class="form-text">
                                    请选择货物是否已被收货地签收
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="order_screenshot" class="form-label">
                                <i class="bi bi-image text-primary"></i> 订单截图 <span class="text-muted">(可选)</span>
                            </label>
                            <input type="file" class="form-control" id="order_screenshot" name="order_screenshot" 
                                   accept="image/*" onchange="previewImage(this, 'screenshotPreview')">
                            <div class="form-text">
                                支持 JPG、PNG、GIF 格式，最大 5MB
                            </div>
                            
                            <!-- 图片预览 -->
                            <div id="screenshotPreview" class="mt-3" style="display: none;"></div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="notes" class="form-label">
                                <i class="bi bi-sticky text-primary"></i> 备注信息 <span class="text-muted">(可选)</span>
                            </label>
                            <textarea class="form-control" id="notes" name="notes" rows="3" 
                                      placeholder="可填写取件码等额外信息"></textarea>
                            <div class="form-text">
                                非必填项，可填写取件码快递单号里边如有多个商品可在这备注信息等其他需要说明的信息
                            </div>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                <i class="bi bi-arrow-counterclockwise"></i> 重置
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-send-fill"></i> 提交报单
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- 报单说明 -->
            <div class="card mt-4">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-info-circle"></i> 报单说明
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6><i class="bi bi-check-circle text-success"></i> 填写要求</h6>
                            <ul class="mb-3">
                                <li>请确保所有必填字段都填写完整</li>
                                <li>收货地和下单平台请准确选择</li>
                                <li>物流单号要准确无误（不超过15位）</li>
                                <li>下单金额请填写实际支付金额</li>
                                <li>订单截图有助于加快审核速度</li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h6><i class="bi bi-clock text-warning"></i> 处理流程</h6>
                            <ul class="mb-3">
                                <li>提交报单后状态为"未结算"</li>
                                <li>管理员审核后进行结算操作</li>
                                <li>结算完成后状态变为"已结算"</li>
                                <li>到货后可修改签收状态和取件码</li>
                                <li>如有问题可联系管理员处理</li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="alert alert-warning mb-0">
                        <i class="bi bi-exclamation-triangle"></i>
                        <strong>重要提示：</strong> 
                        订单提交后，只能修改签收状态和取件码信息，其他信息无法修改。请仔细核对后再提交！
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function resetForm() {
    if (confirm('确定要重置表单吗？')) {
        document.querySelector('form').reset();
        document.getElementById('screenshotPreview').style.display = 'none';
    }
}

// 表单验证
(function() {
    'use strict';
    window.addEventListener('load', function() {
        const forms = document.querySelectorAll('.needs-validation');
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// 物流单号格式检查和长度限制
document.getElementById('tracking_no').addEventListener('input', function() {
    this.value = this.value.replace(/\s+/g, ''); // 移除空格
    
    // 实时显示长度
    const length = this.value.length;
    const feedback = this.nextElementSibling;
    if (length > 18) {
        this.classList.add('is-invalid');
        if (feedback && feedback.classList.contains('form-text')) {
            feedback.innerHTML = `<span class="text-danger"><i class="bi bi-exclamation-triangle"></i> 物流单号不能超过18位，当前：${length}位</span>`;
        }
    } else {
        this.classList.remove('is-invalid');
        if (feedback && feedback.classList.contains('form-text')) {
            feedback.innerHTML = `<i class="bi bi-exclamation-triangle"></i> 请填写快递单号（不超过18位），不要填写订单号`;
        }
    }
});

// 图片预览功能
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    if (!preview) return;
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.innerHTML = `<img src="${e.target.result}" class="img-fluid rounded shadow-sm" style="max-height: 200px;">`;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(input.files[0]);
    } else {
        preview.innerHTML = '';
        preview.style.display = 'none';
    }
}
</script>

<?php include __DIR__ . '/footer.php'; ?>